import React, { useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Form, Button, Input, DatePicker, InputNumber, Select, Modal, Switch, Checkbox, message } from 'antd'
import OperaPrompt from '@/components/OperaPrompt'
import styles from './index.less'
import request from '@/utils/request';
import Selector from './selector'
import { CloudUploadOutlined } from '@ant-design/icons'
import { constant } from 'lodash';
import { useForm } from 'antd/lib/form/util';

const { TextArea } = Input;
const { Option } = Select


const makeNumList = (num: number) => {
    const result = [];
    for (let i = 0; i <= num; i++) {
        let val = String(i).length < 2 ? String('0').concat(String(i)) : String(i)
        result.push(val)
    }
    return result
}

const save = () => {

    const [visable, setVisable] = useState(false);
    const [form] = Form.useForm()

    const closeModal = () => {
        setVisable(false);
    };
    const [skuList, setSkuList] = useState<any[]>([])
    const [isDiscount, setIsDiscount] = useState(false)

    const selectFinish = (selectedGoods: any) => {
        if (!Array.isArray(selectedGoods.sku_list)) {
            return
        }
        console.log(selectedGoods);
        let data = selectedGoods.sku_list.map((item: any) => ({
            sku_title: item.sku_title,
            sale_price: item.sale_price,
            sku_id: item.id,
            group_price: "",
            leader_price: "",
            goods_id: selectedGoods.id,
        }))
        setSkuList(data)
    }


    const skuInput = (skuId: number, val: string, field: string) => {
        let result: any[] = skuList.map((item: any) => {
            return item.sku_id === skuId ? { ...item, [field]: val } : item
        })
        setSkuList(result)
    }
    const someStyle = {
        padding: "0 8px"
    }
    const onFinish = (values: any) => {
        values['start_time'] = values['start_time'].format('YYYY-MM-DD HH:mm:ss');
        values['end_time'] = values['end_time'].format('YYYY-MM-DD HH:mm:ss');
        values['is_single'] = values['is_single'] ? 1 : 0
        values['is_virtual'] = values['is_virtual'] ? 1 : 0
        values['is_recommend'] = values['is_recommend'] ? 1 : 0

        values['sku_list'] = skuList
        values["valid_dhm"] = { d: values["validD"], h: values["validH"], m: values["validM"] }
        values["is_leader_discount"] = isDiscount ? 1 : 0
        request(`/promote/fight_group/save/0`, {
            method: 'POST',
            data: { ...values },
        }).then((result) => {
            message.success(result.message, 1, () => {

            })
            // getList()
        })
    };
    return (
        <PageHeaderWrapper title={false}>
            <Card bordered={false}>

                <OperaPrompt dataList={[
                    "管理员可以在此页添加拼团活动"
                ]} />
                <div style={{ paddingTop: "12px" }}>
                    <Form
                        form={form}
                        labelCol={{ span: 3 }}
                        wrapperCol={{ span: 15 }}
                        onFinish={onFinish}
                        initialValues={{
                            validD: '01',
                            validH: '00',
                            validM: '00'
                        }}
                    >
                        <Form.Item label="活动名称" name="activity_title" help="活动名称将显示在活动列表中，方便商家管理"
                            rules={[{ required: true, message: '活动名称不能为空' }]}>
                            <Input />
                        </Form.Item>

                        <Form.Item label="开始时间" required name="start_time">
                            <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime />
                        </Form.Item>
                        <Form.Item label="结束时间" required name="end_time" help="结束时间不能小于开始时间，也不能小于当前时间">
                            <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime />
                        </Form.Item>

                        <Form.Item label="参团人数" name="join_num" help="最少两人成团">
                            <InputNumber />
                        </Form.Item>
                        <Form.Item label="拼团有效期">
                            <Input.Group>
                                <Form.Item
                                    noStyle
                                    name="validD"
                                >
                                    <Select style={{ width: "80px" }}>
                                        {
                                            makeNumList(30).map((item: any, inx: number) =>
                                                <Option value={item} key={inx}>{item}</Option>)
                                        }
                                    </Select>
                                </Form.Item>
                                <span style={someStyle}>日</span>
                                <Form.Item
                                    noStyle
                                    name="validH"
                                >
                                    <Select style={{ width: "80px" }}>
                                        {
                                            makeNumList(23).map((item: any, inx: number) =>
                                                <Option value={item} key={inx}>{item}</Option>)
                                        }
                                    </Select>
                                </Form.Item>
                                <span style={someStyle}>时</span>
                                <Form.Item
                                    noStyle
                                    name="validM"
                                >
                                    <Select style={{ width: "80px" }}>
                                        {
                                            makeNumList(59).map((item: any, inx: number) =>
                                                <Option value={item} key={inx}>{item}</Option>)
                                        }
                                    </Select>
                                </Form.Item>
                                <span style={someStyle}>分</span>
                            </Input.Group>
                        </Form.Item>

                        <Form.Item label="是否单独购买" style={{ margin: 0 }}>
                            <div style={{ display: "flex" }}>
                                <div style={{ paddingTop: "4px" }}>
                                    <Form.Item noStyle name="is_single" valuePropName="checked">
                                        <Checkbox />
                                    </Form.Item>
                                </div>

                                <div style={{ margin: "0 24px" }}>
                                    <Form.Item label="是否虚拟成团" name="is_virtual" valuePropName="checked">
                                        <Checkbox />
                                    </Form.Item>
                                </div>

                                <Form.Item label="是否推荐" name="is_recommend" valuePropName="checked">
                                    <Checkbox />
                                </Form.Item>
                            </div>
                        </Form.Item>

                        <Form.Item label="限制购买" name="max_buy" help="本次活动中一次最多可购买的商品数量，默认为1">
                            <InputNumber />
                        </Form.Item>

                        <Form.Item label="备注" name="remark">
                            <TextArea rows={3} />
                        </Form.Item>
                        <Form.Item label="团长优惠" >
                            <div style={{ paddingTop: "5px" }}>
                                <Checkbox checked={isDiscount} onChange={(e) => {
                                    setIsDiscount(e.target.checked)
                                }} />
                                <span style={{ paddingLeft: "6px" }}>团长享受优惠价</span>
                            </div>
                            <div style={{ color: "#B2B2B2", fontSize: "12px" }}>开启团长(开团人)优惠后，团长将享受更优惠价格，有助于提高开团率和成团率</div>
                            <table className={styles.myTable}>
                                <thead>
                                    <tr >
                                        <td>商品名称</td>
                                        <td>商品价格(元)</td>
                                        <td>拼团价格(元)</td>
                                        <td style={isDiscount ? {} : { display: "none" }}>团长优惠价(元)</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    {
                                        skuList.map((item: any, inx: number) =>
                                            <tr key={inx}>
                                                <td>{item.sku_title}</td>
                                                <td>￥{item.sale_price}</td>
                                                <td>
                                                    <Input value={item.group_price} onChange={(e) => { skuInput(item.sku_id, e.target.value, 'group_price') }} />
                                                </td>
                                                <td style={isDiscount ? {} : { display: "none" }}>
                                                    <Input value={item.leader_price} onChange={(e) => { skuInput(item.sku_id, e.target.value, 'leader_price') }} />
                                                </td>
                                            </tr>
                                        )
                                    }
                                </tbody>
                            </table>
                            <Button type="primary" onClick={() => { setVisable(true) }}>添加商品</Button>
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 3 }}>
                            <Button type="primary" htmlType="submit">保存</Button>
                            <Button style={{ marginLeft: "8px" }} onClick={() => {
                                history.back()
                            }}>返回</Button>
                        </Form.Item>
                    </Form>
                </div>
            </Card>
            <Modal
                title="商品选择"
                width="60%"
                visible={visable}
                onCancel={closeModal}
                footer={null}
            >
                <Selector close={closeModal} idList={[]} selectFinish={selectFinish} />
            </Modal>
        </PageHeaderWrapper>
    );
};

export default save;